//登录页
class Login {
  constructor() {
    //绑定登录点击事件
    this.$("#profile .btn-danger").addEventListener("click", this.checkLogin);
    //获取?后的地址,并结构数组
    this.returnUrl = location.search.split("=").pop();
    // console.log(location.search.split('='));
    // console.log(this.returnUrl);
  }
  //点击登录的方法
  checkLogin = () => {
    // console.log(11111);
    //获取input框
    let form = document.forms[0].elements;
    //获取登录框和密码框
    let username = form.uname.value.trim();
    let password = form.password.value.trim();
    // console.log(user, password);
    // console.log(form);
    //非空验证
    if (!username || !password) {
      layer.msg("账号密码不能为空...");
      return;
    }

    //设置参数编码方式
    axios.defaults.headers["Content-Type"] =
      "application/x-www-form-urlencoded";
    //发送ajax请求
    let str = `username=${username}&password=${password}`;
    axios
      .post("http://localhost:8888/users/login", str)
      .then((response) => {
        // console.log(response);
        //登陆成功存储token和用户名
        let { status, data } = response;
        // console.log(response);
        if (status != 200 || data.code != 1) {
          layer.msg("账号密码错误...");
          return;
        }
        //登录成功,到local中存储数据
        localStorage.setItem("token", data.token);
        localStorage.setItem("user_id", data.user.id);
        //判断是否从其他页面跳转到登录页面
        // location.href = 'returnUrl' || './list.html';
        let tmpUrl = this.returnUrl || "./list.html";
        // console.log(this.returnUrl);
        //登录成功跳转页面
        location.href = tmpUrl;
      })
      .catch(function (error) {
        // console.log(error);
      });
  };
  //封装获取节点
  $(e) {
    let res = document.querySelectorAll(e);
    return res.length == 1 ? res[0] : res;
  }
}
new Login();
